package com.echo.im.engin.netty.packet;

import com.echo.im.engin.packet.Packet;
import io.netty.buffer.ByteBuf;

/**
 * @author: echo
 * @time: 2024-08-23
 */
public class PacketCodeC {

    private static final int MAGIC_NUMBER = 0x12345678;
    public static final PacketCodeC INSTANCE = new PacketCodeC();
    public ByteBuf encode(ByteBuf byteBuf,Packet packet) {

        //2. 序列化packet
        byte[] bytes = SerializerAlgorithm.DEFAULT.serialize(packet);
        //3. 编码
        //魔数
        byteBuf.writeInt(MAGIC_NUMBER);
        //版本号
        byteBuf.writeByte(packet.getVersion());
        //序列化算法
        byteBuf.writeByte(SerializerAlgorithm.DEFAULT.getSerializerAlgorithm());
        //指令
        byteBuf.writeByte(packet.getCommand());
        //数据长度
        byteBuf.writeInt(bytes.length);
        //数据
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }


    public Packet decode(ByteBuf byteBuf) {
        //1. 跳过魔数
        byteBuf.skipBytes(4);
        //2. 跳过版本号
        byteBuf.skipBytes(1);
        //3. 序列化算法
        byte serializeAlgorithm = byteBuf.readByte();
        //4. 指令
        byte command = byteBuf.readByte();
        //5. 数据长度
        int length = byteBuf.readInt();
        //6. 数据
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);

        Class<? extends Packet> clazz= PacketManager.getPacketClassByCommand(command);

        Serializer serializer = SerializerAlgorithm.getSerializer(serializeAlgorithm);
        if(clazz!=null&& serializer!=null){
            return serializer.deserialize(clazz,bytes);
        }
        return null;
    }



}
